//
//  SJMyQRCodeViewController.swift
//  SJWeiboSwift
//
//  Created by app;e on 15/10/5.
//  Copyright © 2015年 world. All rights reserved.
//
//  我的名片界面

import UIKit

class SJMyQRCodeViewController: UIViewController {
    lazy var iconView: UIImageView = UIImageView()
    
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        view.addSubview(iconView)
        iconView.backgroundColor = UIColor.lightGrayColor()
        iconView.ff_AlignInner(ff_AlignType.CenterCenter, referView: view, size: CGSize(width: 200, height: 200))
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        iconView.image = generateQRCodeImage()
    }

    ///生成二维码图片
    func generateQRCodeImage()->UIImage{
        //1.建立二维码滤镜
        let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
        //2.设置成初始值
        qrFilter.setDefaults()
        //3.通过KVC 设置滤镜信息(字符串要转成NSData)
        qrFilter.setValue("谁动了MyWorld".dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage")
        //4.获取结果
        let ciImage = qrFilter.outputImage!
        //5.放大图片 (默认生成的图片是 27 * 27)
        let transform = CGAffineTransformMakeScale(15, 15)
        let transformImage = ciImage.imageByApplyingTransform(transform)
        
        //6.颜色滤镜
        let colorFilter = CIFilter(name: "CIFalseColor")!
        colorFilter.setDefaults()
        colorFilter.setValue(transformImage, forKey: "inputImage")
        //前景色
        colorFilter.setValue(CIColor(color: UIColor.orangeColor()), forKey: "inputColor0")
        //背景色
        colorFilter.setValue(CIColor(color: UIColor.whiteColor()), forKey: "inputColor1")
        
        let resultImage = colorFilter.outputImage!
        let avatar = UIImage(named: "kuiba.jpg")!
        return insertAvatarImage(UIImage(CIImage: resultImage), avatar: avatar)
    }
    
    ///在二维码图像中增加一个头像
    /**
    二维码有很强的容错性
    - 能够遮挡部分，也可以破损部分，但是，不能破坏或者遮挡定位点！
    */
    func insertAvatarImage(image: UIImage, avatar: UIImage) ->UIImage{
        
        //1.开启图像上下文, 和二维码图像大小一样
        UIGraphicsBeginImageContext(image.size)
        //2.绘图
        //2.1画二维码
        let rect = CGRect(origin: CGPointZero, size: image.size)
        image.drawInRect(rect)
        //2.1画头像
        let w = rect.width*0.25
        let x = (rect.width - w) * 0.5
        let y = (rect.height - w) * 0.5
        avatar.drawInRect(CGRect(x: x, y: y, width: w, height: w))
        
        //3.获取结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        //4.关闭上下文
        UIGraphicsEndImageContext()
        //5.返回结果
        return result
    }
}
